package com.topisv.tms.web.focus;

import java.io.ByteArrayInputStream;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.apache.shiro.SecurityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springside.modules.web.Servlets;

import com.topisv.tms.entity.AreaGroup;
import com.topisv.tms.entity.Customers;
import com.topisv.tms.entity.ShopSource;
import com.topisv.tms.entity.ViewEdiOrder;
import com.topisv.tms.entity.dto.OutstorageInfoDto;
import com.topisv.tms.service.AreaGroupService;
import com.topisv.tms.service.CustomersService;
import com.topisv.tms.service.ShopSourceService;
import com.topisv.tms.service.ViewEdiOrderService;
import com.topisv.tms.service.account.ShiroDbRealm.ShiroUser;
import com.topisv.tms.tools.ExcelUtils;

/**
 * 集发出库信息_control
 * @author ch
 */
@Controller
@RequestMapping(value = "/focusOutInfo")
public class FocusOutInfoController {

	private static final Logger logger = LoggerFactory.getLogger(FocusOutInfoController.class);

	@Autowired
	private CustomersService customersService;
	@Autowired
	private AreaGroupService areaGroupService;
	@Autowired
	private ViewEdiOrderService viewEdiOrderService;
	@Autowired
	private ShopSourceService shopSourceService;
	

	/**
	 * 导向出库查询页面
	 * @param model
	 * @param request
	 * @return
	 */
	@RequestMapping(value = "toFocusOutInfoPage")
	public String toFocusOutInfoPage(Model model, ServletRequest request) {
		try {
			//查出当前用户关联的商家列表
			ShiroUser curUser = (ShiroUser) SecurityUtils.getSubject().getPrincipal();
			List<Customers> customerList=this.customersService.loadCustomerByAuthority(curUser);
			model.addAttribute("customerList",customerList);
			model.addAttribute("userType",curUser.userType);
			
		} catch (Exception e) {
			
			logger.error("error",e);
		}
		return "work/gather/focusOutInfo";
	}
	
	//////////////////////////////////////////////////////////出库数据合计///////////////////////////////////////////////////////////////////////
	//查询出库信息
	@RequestMapping(value = "queryOutInfo")
	public String queryOutInfo(Model model, ServletRequest request) {
		try {
			
			//当前用户关联的商家列表
			ShiroUser curUser = (ShiroUser) SecurityUtils.getSubject().getPrincipal();
			List<Customers> customerList=this.customersService.loadCustomerByAuthority(curUser);
			model.addAttribute("customerList",customerList);
			model.addAttribute("userType",curUser.userType);
			
			Map<String, Object> param = Servlets.getParametersStartingWith(request, "_");
			String warehouseCode=(String)param.get("warehouseCode");
			String shopCode=(String)param.get("shopCode");
			String batchCode=(String)param.get("batchCode");
			String taskCode=(String)param.get("taskCode");
			String sku=(String)param.get("sku");
			
			//时间筛选
			String fromDateStr=(String) param.get("fromDate");
			String toDateStr=(String) param.get("toDate");
			Date fromDate=null;
			Date toDate=null;
			SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
			if(StringUtils.isNotEmpty(fromDateStr)){
				fromDate=sdf.parse(fromDateStr+" 00:00:00");
			}
			if(StringUtils.isNotEmpty(toDateStr)){
				toDate=sdf.parse(toDateStr+" 23:59:59");
			}
			param.put("fromDate", fromDate);
			param.put("toDate", toDate);
			param.put("status", "finish");
			param.put("orderStatus", "ok");
			
			//初始化仓库数据
			String customerCode=(String)param.get("customerCode");
			List<AreaGroup> warehouseList=this.areaGroupService.loadAreaGroupByAuthority(curUser, customerCode);
			model.addAttribute("warehouseList", warehouseList);
			
			//初始化商铺数据
			List<ShopSource> shopList=this.shopSourceService.findByCustomerCode(customerCode);
			model.addAttribute("shopList", shopList); 
			
			//出库信息统计
			List<OutstorageInfoDto> dtoList=this.viewEdiOrderService.loadDtoByParam(param);
			model.addAttribute("dtoList", dtoList);
			
			model.addAttribute("_customerCode", customerCode);
			model.addAttribute("_warehouseCode", warehouseCode);
			model.addAttribute("_shopCode", shopCode);
			model.addAttribute("_batchCode", batchCode);
			model.addAttribute("_taskCode", taskCode);
			model.addAttribute("_sku", sku);
			model.addAttribute("_fromDate", fromDateStr);
			model.addAttribute("_toDate", toDateStr);
			  
		} catch (Exception e) {
			
			logger.error("error",e);
		}
		return "work/gather/focusOutInfo";
	}
	
	/**
	 * 导出_出库数据统计
	 */
	@RequestMapping(value = "expTotal")
	public String expTotal(Model model, ServletRequest request,ServletResponse response){
		FileInputStream f=null;
		OutputStream output=null;
		try {
			Date now=new Date();
			DateFormat df=new SimpleDateFormat("yyyyMMddhhmmss");
			
			//出库信息统计
			Map<String, Object> param = Servlets.getParametersStartingWith(request, "_");
			String fromDateStr=(String) param.get("fromDate");
			String toDateStr=(String) param.get("toDate");
			Date fromDate=null;
			Date toDate=null;
			SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
			if(StringUtils.isNotEmpty(fromDateStr)){
				fromDate=sdf.parse(fromDateStr+" 00:00:00");
			}
			if(StringUtils.isNotEmpty(toDateStr)){
				toDate=sdf.parse(toDateStr+" 23:59:59");
			}
			
			param.put("fromDate", fromDate);
			param.put("toDate", toDate);
			param.put("status", "finish");
			param.put("orderStatus", "ok");
			
			List<OutstorageInfoDto> dtoList=this.viewEdiOrderService.loadDtoByParam(param);
			
			/** 定义导出数据集合 */
			List<Object[]> list = new ArrayList<Object[]>();
			
			for (int i = 0; i < dtoList.size(); i++) {
				try {
					OutstorageInfoDto o=dtoList.get(i);
					Object[] obj = {
							i+1,
							o.getCustomerCode(),
							o.getWarehouseCode(),
							o.getSku(),
							o.getGoodsName(),
							o.getNum(),
						    null
					};
					list.add(obj);
				} catch (Exception e) {
					
					logger.error("error",e);
				}
			}
			
			/** 导出数据 */
			String[] title = { "序号", "商家","仓库","SKU","商品名称","数量"};
			String filepath = df.format(now)+".xls";
			String title_page="出库数据统计";
			ExcelUtils.writeExcel(title, filepath,title_page, df.format(now) , list); // 生成excel
			
			/** 把生成的excel文件读出字节返回给客户端 */
			((HttpServletResponse)response).setHeader("Content-disposition", "attachment; filename="+ new String(filepath.getBytes("gb2312"),"iso8859-1"));
			f = new FileInputStream(ExcelUtils.TEMPPATH+filepath);
			byte[] fb = new byte[f.available()];
			f.read(fb);
			ByteArrayInputStream bais = new ByteArrayInputStream(fb);
			output =((HttpServletResponse)response).getOutputStream();
			int by = 0;
			while ((by = bais.read()) != -1) {
				output.write(by);
			}
			output.flush();
			
		} catch (Exception e) {
			return "error";
		}finally{
			if (output!=null) {
				try { output.close(); } catch (IOException e) {logger.error("error",e);}
			}
			if (f!=null) {
				try { f.close(); } catch (IOException e)  {logger.error("error",e);}
			}
		}
		return null;
	}
	
	
	
//////////////////////////////////////////////////////////订单明细///////////////////////////////////////////////////////////////////////
	
	//查询订单明细
	@RequestMapping(value = "queryDetail")
	public String queryDetail(Model model, ServletRequest request) {
	try {
	
		Map<String, Object> param = Servlets.getParametersStartingWith(request, "_");
		String customerCode=(String)param.get("customerCode");
		String warehouseCode=(String)param.get("warehouseCode");
		String shopCode=(String)param.get("shopCode");
		String batchCode=(String)param.get("batchCode");
		String taskCode=(String)param.get("taskCode");
		String sku=(String)param.get("sku");
		
		//时间筛选
		String fromDateStr=(String) param.get("fromDate");
		String toDateStr=(String) param.get("toDate");
		Date fromDate=null;
		Date toDate=null;
		SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		if(StringUtils.isNotEmpty(fromDateStr)){
		fromDate=sdf.parse(fromDateStr+" 00:00:00");
		}
		if(StringUtils.isNotEmpty(toDateStr)){
		toDate=sdf.parse(toDateStr+" 23:59:59");
		}
		param.put("fromDate", fromDate);
		param.put("toDate", toDate);
		param.put("status", "finish");
		param.put("orderStatus", "ok");
		
		
		//出库信息统计
		List<ViewEdiOrder> infoList=this.viewEdiOrderService.loadByParam(param);
		model.addAttribute("infoList", infoList);
		
		model.addAttribute("_customerCode", customerCode);
		model.addAttribute("_warehouseCode", warehouseCode);
		model.addAttribute("_shopCode", shopCode);
		model.addAttribute("_batchCode", batchCode);
		model.addAttribute("_taskCode", taskCode);
		model.addAttribute("_sku", sku);
		model.addAttribute("_fromDate", fromDateStr);
		model.addAttribute("_toDate", toDateStr);
		
		
		} catch (Exception e) {
			
			logger.error("error",e);
		}
		
		return "work/gather/focusOutInfo_detail";
	}
	
	/**
	 * 导出出库明细
	 */
	@RequestMapping(value = "expDetail")
	public String expDetail_order(Model model, ServletRequest request,ServletResponse response){
		FileInputStream f=null;
		OutputStream output=null;
		try {
			Date now=new Date();
			DateFormat df=new SimpleDateFormat("yyyyMMddhhmmss");
			
			//出库信息统计
			Map<String, Object> param = Servlets.getParametersStartingWith(request, "_");
			String fromDateStr=(String) param.get("fromDate");
			String toDateStr=(String) param.get("toDate");
			Date fromDate=null;
			Date toDate=null;
			SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
			if(StringUtils.isNotEmpty(fromDateStr)){
				fromDate=sdf.parse(fromDateStr+" 00:00:00");
			}
			if(StringUtils.isNotEmpty(toDateStr)){
				toDate=sdf.parse(toDateStr+" 23:59:59");
			}
			param.put("fromDate", fromDate);
			param.put("toDate", toDate);
			param.put("status", "finish");
			param.put("orderStatus", "ok");
			List<ViewEdiOrder> infoList=this.viewEdiOrderService.loadByParam(param);
			
			/** 定义导出数据集合 */
			List<Object[]> list = new ArrayList<Object[]>();
			
			for (int i = 0; i < infoList.size(); i++) {
				try {
					ViewEdiOrder o=infoList.get(i);
					Object[] obj = {
							i+1,
							o.getCustomerCode(),
							o.getWarehouseCode(),
							o.getShopna(),
							o.getBatchCode(),
							o.getOrderno(),
							o.getGoodsName(),
							o.getSku(),
							o.getNum(),
							o.getPrice(),
							o.getRecena(),
							o.getCustna(),
							o.getAddress(),
							(StringUtils.isBlank(o.getMobile())?"":"【"+o.getMobile()+"】")+(StringUtils.isBlank(o.getTeleph())?"":"【"+o.getTeleph()+"】"),
						    null
					};
					list.add(obj);
				} catch (Exception e) {
					
					logger.error("error",e);
				}
			}
			
			/** 导出数据 */
			String[] title = { "序号", "商家","仓库","销售店铺","批次号","能容订单号","商品名", "SKU","数量","价格","收件人","昵称","收件地址","联系电话"};
			String filepath = df.format(now)+".xls";
			String title_page="出库订单明细（集发）";
			ExcelUtils.writeExcel(title, filepath,title_page, df.format(now) , list); // 生成excel
			
			/** 把生成的excel文件读出字节返回给客户端 */
			((HttpServletResponse)response).setHeader("Content-disposition", "attachment; filename="+ new String(filepath.getBytes("gb2312"),"iso8859-1"));
			f = new FileInputStream(ExcelUtils.TEMPPATH+filepath);
			byte[] fb = new byte[f.available()];
			f.read(fb);
			ByteArrayInputStream bais = new ByteArrayInputStream(fb);
			output =((HttpServletResponse)response).getOutputStream();
			int by = 0;
			while ((by = bais.read()) != -1) {
				output.write(by);
			}
			output.flush();
			
		} catch (Exception e) {
			return "error";
		}finally{
			if (output!=null) {
				try { output.close(); } catch (IOException e) {logger.error("error",e);}
			}
			if (f!=null) {
				try { f.close(); } catch (IOException e)  {logger.error("error",e);}
			}
		}
		return null;
	}
		
		
		
		
}
